package com.example.mqttclient;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class HistoryActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private HistoryAdapter adapter;
    private DatabaseHelper dbHelper;
    private TextView totalEmissionView;
    private Timer dataRefreshTimer;
    private LineChart emissionChart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);

        // 初始化视图
        recyclerView = findViewById(R.id.recyclerView);
        totalEmissionView = findViewById(R.id.totalEmission);
        emissionChart = findViewById(R.id.emissionChart);
        // 设置RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new HistoryAdapter(new ArrayList<>());
        recyclerView.setAdapter(adapter);

        // 初始化数据库
        dbHelper = new DatabaseHelper(this);

        // 加载数据
        loadHistoryData();

        startDataRefreshTimer();
    }


    private void startDataRefreshTimer() {
        dataRefreshTimer = new Timer();
        dataRefreshTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                refreshData();
            }
        }, 0, 30000); // 每30秒刷新一次数据
    }

    private void refreshData() {
        runOnUiThread(() -> {
            loadHistoryData();
        });
    }


    private double calculateTotalEmission(List<DatabaseHelper.DeviceUsageRecord> records) {
        double total = 0;
        for (DatabaseHelper.DeviceUsageRecord record : records) {
            total += record.getEmission();
        }
        return total;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.history_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.menu_all) {
            loadHistoryData();
            return true;
        } else if (id == R.id.menu_today) {
            loadTodayData();
            return true;
        } else if (id == R.id.menu_weekly) {
            loadWeeklyData();
            return true;
        } else if (id == R.id.menu_hourly) {
            loadHourlyData();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void loadHistoryData() {
        List<DatabaseHelper.DeviceUsageRecord> records = dbHelper.getAllRecords();
        updateUI(records);
    }

    private void loadTodayData() {
        List<DatabaseHelper.DeviceUsageRecord> records = dbHelper.getTodayRecords();
        updateUI(records);
    }

    private void loadWeeklyData() {
        List<DatabaseHelper.DeviceUsageRecord> records = dbHelper.getWeeklyRecords();
        updateUI(records);
    }

    private void loadHourlyData() {
        List<DatabaseHelper.DeviceUsageRecord> records = dbHelper.getHourlyRecords();
        updateUI(records);
    }

    private void updateUI(List<DatabaseHelper.DeviceUsageRecord> records) {
        // 计算总排放量
        double totalEmission = calculateTotalEmission(records);
        totalEmissionView.setText(String.format("总碳排放量: %.2f kgCO₂", totalEmission));

        // 更新适配器
        adapter.updateData(records);

        // 设置图表
        setupEmissionChart(records);
    }

    private void setupEmissionChart(List<DatabaseHelper.DeviceUsageRecord> records) {
        if (records == null || records.isEmpty()) {
            emissionChart.clear();
            emissionChart.invalidate();
            return;
        }

        // 准备数据
        List<Entry> entries = new ArrayList<>();
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());

        for (int i = 0; i < records.size(); i++) {
            DatabaseHelper.DeviceUsageRecord record = records.get(i);
            entries.add(new Entry(i, (float) record.getEmission()));
        }

        LineDataSet dataSet = new LineDataSet(entries, "碳排放量 (kgCO₂)");
        dataSet.setColor(Color.RED);
        dataSet.setValueTextColor(Color.BLACK);
        dataSet.setCircleColor(Color.RED);
        dataSet.setLineWidth(2f);
        dataSet.setCircleRadius(3f);

        LineData lineData = new LineData(dataSet);
        emissionChart.setData(lineData);

        // 配置图表
        emissionChart.getDescription().setEnabled(false);
        XAxis xAxis = emissionChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);

        YAxis leftAxis = emissionChart.getAxisLeft();
        leftAxis.setAxisMinimum(0f);
        emissionChart.getAxisRight().setEnabled(false);

        // 添加动画
        emissionChart.animateY(1000);
        emissionChart.invalidate();
    }
    @Override
    protected void onDestroy() {
        if (dataRefreshTimer != null) {
            dataRefreshTimer.cancel();
            dataRefreshTimer = null;
        }
        dbHelper.close();
        super.onDestroy();
    }
}